const mongoose = require('mongoose');
const COLLECTIONS = require('./collections');

// 产品评论模式
const ReviewSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  name: {
    type: String,
    required: true
  },
  rating: {
    type: Number,
    required: true,
    min: 1,
    max: 5
  },
  comment: {
    type: String,
    required: true
  },
  images: [String]
}, { timestamps: true });

// 产品模式
const ProductSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  description: {
    type: String,
    required: true
  },
  // 所属店铺
  shop: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Shop',
    required: true
  },
  price: {
    type: Number,
    required: true,
    default: 0
  },
  originalPrice: {
    type: Number,
    default: 0
  },
  images: [String],
  mainImage: String,
  brand: {
    type: String,
    required: true
  },
  category: {
    type: String,
    required: true
  },
  subcategory: String,
  tags: [String],
  countInStock: {
    type: Number,
    required: true,
    default: 0
  },
  rating: {
    type: Number,
    default: 0
  },
  numReviews: {
    type: Number,
    default: 0
  },
  isFeatured: {
    type: Boolean,
    default: false
  },
  isOnSale: {
    type: Boolean,
    default: false
  },
  salePrice: {
    type: Number
  },
  salesCount: {
    type: Number,
    default: 0
  },
  specifications: {
    type: Map,
    of: String
  },
  // 可选择的规格（如颜色、容量）
  specs: {
    type: Map,
    of: [String]
  },
  reviews: [ReviewSchema]
}, {
  timestamps: true
});

// 创建索引以支持搜索和性能优化
ProductSchema.index({ name: 'text', description: 'text', brand: 'text', category: 'text', tags: 'text' });

// 基础查询索引
ProductSchema.index({ shop: 1 });
ProductSchema.index({ category: 1 });
ProductSchema.index({ brand: 1 });
ProductSchema.index({ price: 1 });
ProductSchema.index({ rating: -1 });
ProductSchema.index({ salesCount: -1 });
ProductSchema.index({ createdAt: -1 });
ProductSchema.index({ updatedAt: -1 });

// 复合索引优化常见查询
ProductSchema.index({ category: 1, shop: 1 });
ProductSchema.index({ brand: 1, shop: 1 });
ProductSchema.index({ shop: 1, category: 1, price: 1 });
ProductSchema.index({ shop: 1, createdAt: -1 });
ProductSchema.index({ category: 1, price: 1 });
ProductSchema.index({ category: 1, rating: -1 });
ProductSchema.index({ isFeatured: 1, rating: -1 });
ProductSchema.index({ isOnSale: 1, salePrice: 1 });
ProductSchema.index({ countInStock: 1 });

// 管理后台查询优化
ProductSchema.index({ shop: 1, updatedAt: -1 });
ProductSchema.index({ category: 1, updatedAt: -1 });
ProductSchema.index({ brand: 1, updatedAt: -1 });

const Product = mongoose.model('Product', ProductSchema, COLLECTIONS.PRODUCTS);

module.exports = Product; 